﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UDPComm;
using System.Threading;
using Newtonsoft.Json;
using System.IO;
namespace NetWorkTest
{
    public partial class Form1 : Form
    {
        UDPClient udp_client = new UDPClient();
        TCPClient tcp_client;// = new TCPClient();
        private delegate void InvokeDelegate();
        string ip = "";
        JsonCmd send_data = new JsonCmd();
        byte[] sendbyte = new byte[1024];
        int sendlen = 0;
        bool udp_flag = false,GET_IP = false,tcp_flag = false;
        byte[] recv_buf ;
        int recvlen = 0;
        Thread th_tcp ;
        public Form1()
        {
            InitializeComponent();
            tcp_client = new TCPClient();


        }

        private void btn_send_Click(object sender, EventArgs e)
        {

            
            StringWriter sw = new StringWriter();
            JsonWriter writer = new JsonTextWriter(sw);
            //string hostname = Dns.GetHostName();
            // IPHostEntry localhost = Dns.GetHostByName(hostname);
            //IPAddress localaddr = localhost.AddressList[0];
            writer.WriteStartObject();
            writer.WritePropertyName("id");
            writer.WriteValue(1);
            writer.WritePropertyName("cmd");
            writer.WriteValue(1);
            writer.WritePropertyName("data");
            writer.WriteValue(send_data.data);
            writer.WritePropertyName("respone");
            writer.WriteValue(0);
            writer.WriteEndObject();
            writer.Flush();
            string jsonText = sw.GetStringBuilder().ToString();
            byte[] by = Encoding.ASCII.GetBytes(jsonText);
            tcp_client.sendTcpData(by, by.Length);
        }

        private void btn_discovery_Click(object sender, EventArgs e)
        {
            udp_client.Send("{\"id\":1,\"cmd\":1,\"data\":\"FE013F3F\",\"respone\":0}");
            if (udp_flag == false)
            {
                var th1 = new Thread(WaitUdpResp);
                th1.Start();
                udp_flag = true;
            }


        }

        private void textIP_TextChanged(object sender, EventArgs e)
        {
            this.ip = this.textIP.Text;
        }
        public  void InvokeUpdateIP()
        {
            this.textIP.Text = ip;
        }
        public void InvokeUpdateRecv()
        {
            string data="";
            for (int i = 0; i < recvlen; i++)
            {
                data += recv_buf[i].ToString("X2");// Convert.ToString(recv_buf[i], 16);
            }
            this.textRecv.AppendText(System.Environment.NewLine + Encoding.ASCII.GetString(recv_buf));
        }
        public void WaitUdpResp(){
            while(true){
                JsonCmd json;
                json  = JsonConvert.DeserializeObject<JsonCmd>(udp_client.UdpReceiver());
                ip = json.data;
                this.Invoke(new InvokeDelegate(InvokeUpdateIP));

            }
           
        }
        public void WaitTcpResp()
        {
            while (true)
            {
                recv_buf = new byte[1024];
                recvlen = tcp_client.getTcpData(ref recv_buf);
                if (recvlen == -1)
                    break;
                this.Invoke(new InvokeDelegate(InvokeUpdateRecv));

            }

        }
        private void btn_tcp_conn_Click(object sender, EventArgs e)
        {
            if (tcp_flag == false)
            {
                if (tcp_client.StartConnect(this.ip) == 0)
                {
                    this.btn_tcp_conn.Text = "断开连接";
                    tcp_flag = true;

                    th_tcp = new Thread(WaitTcpResp);
                    th_tcp.Start();
            
            
                }
                else
                {

                }
            }
            else
            {
                if (tcp_client.StartClose() == 0)
                {
                    this.btn_tcp_conn.Text = "tcp连接";
                    tcp_flag = false;
                    th_tcp.Abort();

                }
            }
        }

        private void btn_checksum_Click(object sender, EventArgs e)
        {
            string check_sum_str="";
            try
            {
              send_data.id = int.Parse(this.text_id.Text);
            send_data.cmd = int.Parse(this.text_cmd.Text);
            check_sum_str = this.textData.Text.Trim();// this.list_data.Text;
            

            byte check_sum = 0;
            //byte[] by =  Encoding.UTF8.GetBytes(check_sum.Trim());
            int length = check_sum_str.Length / 2;
            int index = 0;
            byte[] data = new byte[length];
            //byte[] send_byte = new byte[length+3];
            for (int i = 0; i < check_sum_str.Length; i += 2)
            {
                string str = check_sum_str.Substring(i, 2);
                data[index] = (byte)Convert.ToInt32(str, 16);
                index++;
            }
            check_sum = data[0];
            for (int i = 1; i < data.Length; i++)
            {
                check_sum ^= data[i];
            }
 
            this.text_checksum.Text = check_sum.ToString("X2");// Convert.ToString(check_sum, 16);
            this.text_len.Text = length.ToString("X2"); Convert.ToString(length, 16);

            sendbyte[0] = (byte)Convert.ToInt32(this.text_fh.Text, 16);
            sendbyte[1] = (byte)Convert.ToInt32(this.text_len.Text, 16);
  /*          for (int i = 0; i < data.Length; i++)
            {
                sendbyte[i + 2] = data[i];
            }
            sendbyte[data.Length+2] = check_sum;
            this.sendlen = data.Length+3;*/
            send_data.data =this.text_fh.Text + this.text_len.Text + this.textData.Text + this.text_checksum.Text;//int.Parse(this.text_id.Text);
            send_data.respone = 0;//int.Parse(this..Text);
            this.textSend.Text = send_data.data;
            //byte[] test = Encoding.ASCII.GetBytes(this.textSend.Text);
            }
            catch (Exception err)
            {
                System.Windows.Forms.MessageBox.Show(err.ToString(), "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }



        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            this.textRecv.Clear();
        }

 
    }
}
